package com.mlk.good.api;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.mlk.core.component.page.Pager;
import com.mlk.core.util.ServerResponse;
import com.mlk.good.lib.SybConstants;
import com.mlk.good.lib.SybUtil;
import com.mlk.good.po.EngGoodOrder;
import com.mlk.good.service.EngGoodOrderService;
import com.mlk.good.vo.EngGoodOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

@RestController
@Slf4j
@RequestMapping("/api/engGood/order")
public class EngGoodOrderAPI {

    @Resource
    private EngGoodOrderService engGoodOrderService;

    /**
     * 订单预先估算
     * 传递的参数
     * openId good_id paramId , num
     * @return
     */
    @PostMapping("calculateOrderPrice")
    public ServerResponse calculateOrderPrice(EngGoodOrderVO vo){
        return this.engGoodOrderService.calculateOrderPrice(vo);
    }

    /**
     * 初始化订单
     * @return
     */
    @PostMapping("initOrder")
    public ServerResponse init(EngGoodOrder order){
        return this.engGoodOrderService.initOrder(order);
    }

    /**
     * 取消订单
     * @return
     */
    @GetMapping("cancelOrder")
    public ServerResponse cancelOrder(String orderCode){
        return this.engGoodOrderService.cancelOrder(orderCode);
    }


    /**
     * 根据订单的状态查询订单
     * @return
     */
    @GetMapping("queryOrder")
    public ServerResponse queryOrder(String openId,Integer status){
        return this.engGoodOrderService.queryOrder(openId,status);
    }

    /**
     * 查询已经完成的订单
     * @param openId
     * @return
     */
    @GetMapping("queryFinishedOrder")
    public Pager queryFinishedOrder(String openId){
        return this.engGoodOrderService.queryFinishedOrder(openId);
    }

    /**
     * 预支付
     * @return
     */
    @GetMapping("prePayCheck")
    public ServerResponse prePayCheck(String openId,String orderCode){
        return this.engGoodOrderService.prePayCheck(openId,orderCode);
    }

    /**
     * 订单支付
     * @return
     */
    @PostMapping("payOrder")
    public ServerResponse payOrder(String orderCode){
        return this.engGoodOrderService.payOrder(orderCode);
    }

    /**
     * 微信回调的函数
     * @return
     * @throws WxPayException
     */
    @PostMapping("/notify/order")
    public String parseOrderNotifyResult(HttpServletRequest request, HttpServletResponse response) throws WxPayException, IOException {
        log.error("微信回调支付接口");
        request.setCharacterEncoding("gbk");//通知传输的编码为GBK
        response.setCharacterEncoding("gbk");
        TreeMap<String,String> params = getParams(request);//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        try {
            boolean isSign = SybUtil.validSign(params, SybConstants.SYB_APPKEY);// 接受到推送通知,首先验签
            System.out.println("验签结果:"+isSign);
            log.error("param=====>"+params);
            if(isSign){
                this.engGoodOrderService.handleWxPayOrderNotifyResult(params);
            }
            //验签完毕进行业务处理
        } catch (Exception e) {//处理异常
            // TODO: handle exception
            e.printStackTrace();
        }
        finally{//收到通知,返回success
            response.getOutputStream().write("success".getBytes());
            response.flushBuffer();
        }

        return null;
    }

    /**
     * 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
     * @param request
     * @return
     */
    private TreeMap<String, String> getParams(HttpServletRequest request){
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for(Object key:reqMap.keySet()){
            String value = ((String[])reqMap.get(key))[0];
            System.out.println(key+";"+value);
            map.put(key.toString(),value);
        }
        return map;
    }

    /**
     * 查询订单详情
     * @return
     */
    @GetMapping("getOrderDetail")
    public ServerResponse getOrderDetail(String orderCode){
        return this.engGoodOrderService.getOrderDetail(orderCode);
    }

    /**
     * 客户确认订单
     * @return
     */
    @PostMapping("customConfirmOrder")
    public ServerResponse customConfirmOrder(String orderCode){
        return this.engGoodOrderService.customConfirmOrder(orderCode);
    }

}
